package com.token.iot.bratterycharging.gateway.sender;

import java.util.Map;
import java.util.concurrent.CountDownLatch;

import org.springframework.stereotype.Component;

import com.outstanding.framework.core.Logger;
import com.outstanding.framework.core.PendingException;
import com.outstanding.framework.log.LoggerFactory;
import com.token.iot.bratterycharging.gateway.AbstractSender;
import com.token.iot.bratterycharging.gateway.ChannelHandlerContextManager;
import com.token.iot.bratterycharging.gateway.ResCode;
import com.token.iot.bratterycharging.gateway.Semaphore;
import com.token.iot.bratterycharging.gateway.SemaphoreManager;
import com.token.iot.bratterycharging.gateway.Sender;
import com.token.iot.bratterycharging.gateway.utils.ByteUtil;

import io.netty.channel.ChannelHandlerContext;


/**
 * 获取ICCID以及软硬件版本号
 * @author chenzhixuan
 *
 */
@Component("AIDSender")
public class AIDSender extends AbstractSender{
	
	
	
	private static ChannelHandlerContextManager manager = new ChannelHandlerContextManager();
	
	private static Logger loger = LoggerFactory.getLogger(AIDSender.class);
	
	@Override
	public Object send(String imei,Map<String,String> params)  throws PendingException {
		 //查找对应的HandlerContext
		ChannelHandlerContext context = manager.getChannelHandlerContextByImei(imei);
		
		String command =code+"000000/";
		byte[] c = ByteUtil.addFlag(command.getBytes());
		context.writeAndFlush(c);
		String key = imei+"@000000";
		//信号量
		Semaphore semaphore = SemaphoreManager.registerCommand(key, this);
		try {
			semaphore.await();
		} catch (InterruptedException e) {
			loger.error(e);
			throw new PendingException(ResCode.semaphoreTimeOut);
		}
		String response =  semaphore.getResponse();
		int post  =response.indexOf("#/#");
		int lastpost = response.lastIndexOf("#/#");
		
		String iccid =response.substring(13,post);
		loger.info("the imei ="+iccid);
		String softVersion = response.substring(post+3,lastpost);
		String deviceVersion = response.substring(lastpost+3);
		return iccid;
		
	}

}
